<template>
<div class="station-mana">
  <unfold>
    <template v-slot:tree-list>
      <tree-list ref="treeList" head-name="所在位置" head-icon="iconfont icontubiao-38" edit-url="/main/system/organize-structure"
                 :list="treeListCopy" @getTree="getTree" @setAct="setAct" isOrganize></tree-list>
    </template>
    <template v-slot:content>
      <div class="relative-position full-height page-content">
        <div class="form-inline">
          <q-btn v-if="!isHuawei" @click="openAddOrEditDialog('add', treeActItem)" class="margin-r-10  margin-t-20" outline color="primary" label="添加工位" />
          <q-space />
          <select-input ref="selectInput"
            class="margin-t-20"
            :list="searchCondition" @search="inputSearch" @clearSearchVal="clearSearchVal"></select-input>
        </div>
        <q-table
          :data="tableData" :columns="selColumns"
          row-key="name" class="myTable scroll stick-last-col"
          :loading="tableLoading"
          :pagination="{rowsPerPage: 0}" hide-bottom
          no-data-label="暂无数据"
          @request="onRequest">
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td key="opname" :props="props">{{ props.row.opname }}</q-td>
              <q-td key="opdesc" :props="props">{{ props.row.opdesc }}</q-td>
              <q-td key="organize" :props="props">{{ props.row.parentName }}</q-td>
              <q-td key="remark" :props="props">{{ props.row.remark || '--' }}</q-td>
              <q-td key="operate" :props="props" v-if="!isHuawei" style="width: 100px">
                <table-btn btnType="edit" @click="openAddOrEditDialog('edit', props.row)"/>
                <table-btn btnType="delete" :disable="!!props.row.locationNum" @click="delDialog(props.row)" :tips="`确定要删除${props.row.opdesc}吗？`"/>
              </q-td>
            </q-tr>
          </template>
        </q-table>
        <pagination v-model="pageCur" :page-size="pageSize" :total="total" @changePage="pageChange"
                    @changePageSize="changePageSize"/>
      </div>
    </template>
  </unfold>
<!--  添加编辑弹框-->
  <add-edit-dialog ref="addEditDialog" :org-tree-opt="treeList" @submit="submit"></add-edit-dialog>
</div>
</template>

<script>
import { getOrganizeNested } from 'src/boot/factory/organize'
import { getStation, importFile, addStation, editStation, delStation } from 'src/boot/factory/station'
import { defaultSchemesClearer } from 'src/assets/js/util'
import TreeList from 'src/components/tree-list/list'
import Unfold from 'src/components/unfold'
import Pagination from 'src/components/pagination'
import SelectInput from 'src/components/select-input'
import AddEditDialog from './components/add-edit-station-dialog'
import refreshMixin from '../../assets/js/refresh-mixin'
import { mapGetters } from 'vuex'
export default {
  name: 'station-mana',
  mixins: [refreshMixin],
  data () {
    return {
      treeList: [], // 左侧列表树的数据
      treeListCopy: [], // 去掉default数据的树结构
      treeActItem: {},
      // 筛选
      // 搜索条件
      searchCondition: [{ id: 'opName', name: '工位编码' }, { id: 'opDesc', name: '工位名称' }],
      opName: '', // 工位编码搜索值
      opDesc: '', // 工位名称搜索值
      templateUrl: '../../statics/file/company.xls', // 企业信息模板地址
      // table
      tableLoading: false, // table加载时使用
      tableData: [], // table数据
      columns: [ // 所有标题
        { name: 'opname', align: 'left', label: '工位编码', field: 'opname', check: true },
        { name: 'opdesc', align: 'left', label: '工位名称', field: 'opdesc', check: true },
        { name: 'organize', align: 'left', label: '所在位置', field: 'organize', check: true },
        { name: 'remark', align: 'left', label: '备注', field: 'remark', check: true },
        { name: 'operate', align: 'center', label: '操作', field: 'operate', check: true }
      ],
      columnOptionShow: false, // 设置右侧设置表格头的显示与隐藏
      parentObj: {},
      // 分页
      pageCur: 1, // 页码
      pageSize: 15, // 每页多少条
      total: 0, // 一共多少条
      pages: 5 // 一共多少页
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    // 选中的标题
    selColumns () {
      if (this.isHuawei) {
        return this.columns.filter(item => {
          return item.name !== 'operate'
        })
      }
      return this.columns.filter(item => {
        return item.check
      })
    },
    isHuawei () {
      return this.userInfo.channel === 'hw' && this.userInfo.client_id === 'huawei_iot_stage_app'
    }
  },
  created () {
    this.getInfo()
  },
  methods: {
    /**
     * 全局刷新数据
     * author: xueli
     */
    refreshInfo () {
      this.pageCur = 1
      this.pageSize = 15
      // 清除选中值
      this.$refs.treeList.activeId = this.$refs.treeList.treeList[0].idHash
      this.treeActItem = this.treeListCopy[0]
      // this.$refs.treeList.activeId = null
      // this.treeActItem = {}
      this.getTree()
      this.$refs.selectInput.clearSearchVal()
    },
    // 初始化数据
    getInfo () {
      this.getTree()
      // this.onRequest()
    },
    getTree () {
      getOrganizeNested().then(res => {
        this.treeList = res.data
        this.treeListCopy = defaultSchemesClearer.clear(res.data)
        if (this.treeListCopy.length > 0) {
          this.treeActItem = this.treeListCopy[0]
          this.$nextTick(() => {
            this.$refs.treeList.activeId = this.$refs.treeList.treeList[0].idHash
          })
        }
      }).then(res => {
        this.onRequest()
      })
    },
    // 获取table数据
    onRequest () {
      let info = {
        opName: this.opName,
        opDesc: this.opDesc,
        schemeId: this.treeActItem.id ? this.treeActItem.id : 0,
        level: this.treeActItem.level ? this.treeActItem.level : 0,
        pageIndex: this.pageCur,
        pageSize: this.pageSize
      }
      this.tableLoading = true
      // 获取企业列表
      getStation(info).then((res) => {
        this.tableData = res.data.list
        this.pageCur = res.data.pageIndex
        this.total = res.data.total
        this.pages = res.data.pageTotal
      }).finally(() => {
        this.tableLoading = false
      })
    },
    // 搜索
    inputSearch (item, searchVal) {
      this.searchCondition.forEach(i => {
        this[i.id] = ''
      })
      this[item.id] = searchVal
      this.onRequest()
    },
    // 翻页
    pageChange (page) {
      this.pageCur = page
      this.onRequest()
    },
    // 更换每页多少条
    changePageSize (pageSize) {
      this.pageCur = 1
      this.pageSize = pageSize
      this.onRequest()
    },
    // 清空搜索值
    clearSearchVal () {
      this.searchCondition.forEach(i => {
        this[i.id] = ''
      })
      this.onRequest()
    },
    // 重置tree数据
    initTree (info, open = true) {
      return info.map(item => {
        if (item.children && item.children.length > 0) {
          item.children = this.initTree(item.children)
        }
        return {
          ...item,
          open
        }
      })
    },
    // 存储当前选中的树结构数据
    setAct (item) {
      this.treeActItem = item
      this.onRequest()
    },
    // 打开添加编辑弹框
    openAddOrEditDialog (state = 'add', item) {
      let treeActItem
      if (state === 'add') {
        if (!(this.treeActItem.id || this.treeActItem.level)) {
          this.$message.warning('请先选择组织')
          return false
        }
        if (this.treeActItem.level === 1) {
          this.$message.warning('分厂下不能创建工位')
          return false
        }
        treeActItem = JSON.parse(JSON.stringify(this.treeActItem))
      } else if (state === 'edit') {
        this.findChild(this.treeList, item.parentId)
        treeActItem = this.parentObj
      }
      this.$nextTick(() => {
        this.$refs.addEditDialog.showDialog(state, treeActItem, item)
      })
    },
    // 找到下面一级的子集id
    findOneChild (data, hash) {
      let result = null
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (item.hash === hash) {
          result = item
        }
      }
      return result
    },
    // 找到下面的所有子集id
    // 通过id检索
    findChild (data, parentId) {
      const t = data
      t.map(v => {
        this.findworkShop(v, parentId)
      })
    },
    findworkShop (val, parentId) {
      if (val.id === parentId) {
        this.parentObj = val
      } else if (val.children) {
        val.children.map(j => this.findworkShop(j, parentId))
      } else {
        this.parentObj = {}
      }
    },
    findTreeAct (treeList, treeActItem) {
      let result = null
      for (let i = 0; i < treeList.length; i++) {
        let item = treeList[i]
        if (item.hash === treeActItem.hash) {
          result = item
          break
        }
        if (item.children && item.children.length > 0) {
          result = this.findTreeAct(item.children, treeActItem)
        }
        if (result !== null) {
          break
        }
      }
      return result
    },
    // 提交添加编辑结果
    submit (state, param, organize) {
      let params, ids
      switch (state) {
        case 'add':
          let treeActItems = this.findTreeAct(this.treeList, organize)
          ids = this.getAddParamsId(treeActItems)
          params = {
            ...param,
            ...ids
          }
          addStation(params).then(res => {
            this.onRequest()
            this.$refs.addEditDialog.hideDialog()
            this.$message.success(`添加成功`)
          }).finally(() => {
            this.$refs.addEditDialog.submitting = false
          })
          break
        case 'edit':
          let treeActItem = this.findTreeAct(this.treeList, organize)
          ids = this.getAddParamsId(treeActItem)
          console.log(ids)
          console.log(this.treeList)
          params = {
            ...param,
            ...ids
          }
          editStation(params).then(res => {
            this.onRequest()
            this.$refs.addEditDialog.hideDialog()
            this.$message.success(`编辑成功`)
          }).finally(() => {
            this.$refs.addEditDialog.submitting = false
          })
          break
      }
    },
    // 添加组织，查找plantId、workshopId、lineId、equipgroupId
    getAddParamsId (treeActItem) {
      let params = {}, workshopItem, lineItem, equipgroupItem
      switch (treeActItem.level) {
        case 1:
          workshopItem = treeActItem.children.find(item => item.label === 'default')
          lineItem = workshopItem.children.find(item => item.label === 'default')
          equipgroupItem = lineItem.children.find(item => item.label === 'default')
          params = {
            plantId: treeActItem.id,
            workshopId: workshopItem.id,
            lineId: lineItem.id,
            equipgroupId: equipgroupItem.id
          }
          break
        case 2:
          lineItem = treeActItem.children.find(item => item.label === 'default')
          equipgroupItem = lineItem.children.find(item => item.label === 'default')
          params = {
            plantId: treeActItem.plantId,
            workshopId: treeActItem.id,
            lineId: lineItem.id,
            equipgroupId: equipgroupItem.id
          }
          break
        case 3:
          equipgroupItem = treeActItem.children.find(item => item.label === 'default')
          params = {
            plantId: treeActItem.plantId,
            workshopId: treeActItem.workshopId,
            lineId: treeActItem.id,
            equipgroupId: equipgroupItem.id
          }
          break
        case 4:
          params = {
            plantId: treeActItem.plantId,
            workshopId: treeActItem.workshopId,
            lineId: treeActItem.lineId,
            equipgroupId: treeActItem.id
          }
          break
      }
      return params
    },
    // 删除弹框
    delDialog (item) {
      const params = {
        id: item.id,
        level: item.level
      }
      delStation(params).then(() => {
        this.$message.success(`删除${item.opdesc}成功`)
        this.onRequest()
      })
    },
    // 批量导入上传文件
    importFile (event) {
      this.$q.loading.show()
      importFile(event.target.files).then((res) => {
        this.$q.loading.hide()
        this.$q.dialog({
          title: '提示',
          message: res.message
        })
      })
    }
  },
  components: {
    Unfold,
    TreeList,
    Pagination,
    SelectInput,
    AddEditDialog
  }
}
</script>

<style scoped lang="stylus">
  >>>.right-part{
    padding 0 0 20px !important
  }
.station-mana{
  .myTable .q-table__middle{
    max-height calc(100vh - 500px)
  }
}
</style>

<style lang="stylus">
.station-mana{
  .myTable .q-table__middle{
    max-height calc(100% - 42px)
  }
}
</style>
